<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>群聊</title>
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script type="text/javascript">
        var stompClient = null;
        //切换各个组件的显示与隐藏
        function show(flag) {
            $("#connect").prop("disabled", flag);
            $("#disconnect").prop("disabled", !flag);
            if (flag==true) {
                $("#chatRoom").show();//显示聊天室
                $("#user").text($("#name").val()); //显示用户名
            }else {
                $("#chatRoom").hide();//隐藏聊天室
            }
        }
        //连接到WebSocket服务器
        function connectWebSocket() {
            if (!$("#name").val()) {
                alert("请输入用户名！")
                return;
            }
            var url = "http://localhost:8080/webSocket";
            var socket = new SockJS(url);
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) { //连接成功的回调函数
                console.log("frame:"+frame)
                show(true);
                debugger
                //本次连接的订阅消息，订阅服务端发送目标URL为/topic/receiveAll的消息
                stompClient.subscribe('/topic/receiveAll', function (data) { //data代表接收服务端发送过来的消息
                    showMsg(JSON.parse(data.body)); //展示接收到的消息
                });
            });
        }

        function showMsg(message) { //展示消息
            $("#chating").append("<div>" + message.name+":"+message.content + "</div>");
        }

        function closeWebSocket() { //关闭连接
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            show(false);
        }
        function sendMsg() { //客户端发送消息
            stompClient.send("/app/sendAll",{}, //注意该路径必须要以/app为前缀
                //发送内容是JSON格式的字符串
                JSON.stringify({'name': $("#name").val(),'content':$("#content").val()}));
            $("#content").val("");
        }


        $(function () {
            $( "#connect" ).click(function() { connectWebSocket(); });
            $( "#disconnect" ).click(function() { closeWebSocket(); });
            $( "#send" ).click(function() { sendMsg(); });
        });
    </script>

</head>
<body>
<div>
    <label for="name">用户名：</label>
    <input type="text" id="name" placeholder="用户名">
    <button id="connect" type="button">进入聊天室</button>
    <button id="disconnect" type="button" disabled="disabled">退出聊天室</button>
</div>
<br/>
<div id="chatRoom" style="display: none;">

    <div id="chating" style="border:1px solid #ccc;width:400px;height:400px;">

    </div>
    <br/>
    <div>
        <label for="name"><span id="user"></span>说：</label>
        <input type="text" id="content" placeholder="请输入聊天内容">
        <button id="send" type="button">发送</button>
    </div>
</div>
</body>
</html>